package goredis

import (
	"context"
	"gitee.com/masaichi/mredis/mstruct"
	"time"
)

type StringOperation struct {
	ctx context.Context
	mstruct.MCacheConfig
}

func NewStringOperation(config mstruct.MCacheConfig) *StringOperation {
	return &StringOperation{ctx: context.Background(), MCacheConfig: config}
}

func (this *StringOperation) Set(key string, value interface{}, attrs ...*OperationAttr) *InterfaceResult {
	exp := OperationAttrs(attrs).Find(ATTR_EXPIRE).UnWrapDefault(time.Second * 0).(time.Duration)
	return NewInterfaceResult(Redis(this.MCacheConfig).Set(this.ctx, key, value, exp).Result())
}

func (this *StringOperation) SetNx(key string, value interface{}, attrs ...*OperationAttr) *InterfaceResult {
	exp := OperationAttrs(attrs).Find(ATTR_EXPIRE).UnWrapDefault(time.Second * 0).(time.Duration)
	return NewInterfaceResult(Redis(this.MCacheConfig).SetNX(this.ctx, key, value, exp).Result())
}

//如果有值，则执行，常用于开关业务，比如新闻缓存，有key的走缓存逻辑
//标记业务数据，多个步骤删除数据，第一步 软删除 第二步 如果setxx为true，则数据库删除
func (this *StringOperation) SetXx(key string, value interface{}, attrs ...*OperationAttr) *InterfaceResult {
	exp := OperationAttrs(attrs).Find(ATTR_EXPIRE).UnWrapDefault(time.Second * 0).(time.Duration)
	return NewInterfaceResult(Redis(this.MCacheConfig).SetXX(this.ctx, key, value, exp).Result())
}

func (this *StringOperation) Get(key string) *StringResult {
	return NewStringResult(Redis(this.MCacheConfig).Get(this.ctx, key).Result())
}

//删除缓存
func (this *StringOperation) Del(key string) {
	Redis(this.MCacheConfig).Del(this.ctx, key)
}
